package com.nowcoder.community.advice;

import com.nowcoder.community.utils.CommunityUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@ControllerAdvice(annotations = Controller.class)
@Slf4j
public class ExceptionAdvice {

    @ExceptionHandler
    public void handleException(Exception e, HttpServletRequest request, HttpServletResponse response) throws IOException {
        log.error("服务器发生异常"
                + "请求路径：" + request.getRequestURI() + ", "
                + "异常信息：" + e.getMessage());
        if (request.getHeader("X-Requested-With").equals("XMLHttpRequest")){
            // 异步请求发生异常
            response.setContentType("application/plain;charset=utf-8");
            PrintWriter writer = response.getWriter();
            writer.print(CommunityUtils.getJsonString(500, e.getMessage()));
        }else {
            response.sendError(500);
        }
    }
}
